package edu.pitt.dbmi.odie.gapp.gwt.server.foundry;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.allen_sauer.gwt.log.client.Log;

import edu.pitt.dbmi.odie.gapp.gwt.server.util.rest.ODIE_NcboRestUtils;


// edu.pitt.dbmi.odie.gapp.gwt.server.foundry.ODIE_FoundryServlet

@SuppressWarnings("serial")
public class ODIE_FoundryServlet extends HttpServlet {

	private static final String NCBO_ONTOLOGIES_URL = "http://rest.bioontology.org/bioportal/ontologies";

	public static final String NCBO_ONTOLOGY_CLASS_URL_PREFIX = "http://rest.bioontology.org/bioportal/concepts";
	
	public static final int DEFAULT_BUFFER_SIZE = 1024 ;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		InputStream is = null;
		String urlName = null;

		if (req.getParameter("clsId") != null
				&& req.getParameter("ontologyId") != null) {
			urlName = NCBO_ONTOLOGY_CLASS_URL_PREFIX + "/"
					+ req.getParameter("ontologyId") + "/"
					+ req.getParameter("clsId");
		} else if (req.getParameter("ontologyId") != null) {
			urlName = NCBO_ONTOLOGY_CLASS_URL_PREFIX + "/"
					+ req.getParameter("ontologyId") + "/root";
			is = ODIE_NcboRestUtils.getInputStream(urlName);
		} else {
			urlName = NCBO_ONTOLOGIES_URL;
		}
		
		Log.debug("ODIE_FoundryServlet reading url ==>\n" + urlName) ;
		int maxReadTries = 10 ;
		int readTries = 0 ;
		String payLoad = null ;
		while (payLoad == null && readTries < maxReadTries) {
			payLoad = ODIE_NcboRestUtils.getPayLoad(urlName) ;
			readTries++ ;
		}
		
		if (payLoad != null) {
			resp.getOutputStream().write(payLoad.getBytes()) ;
			resp.getOutputStream().flush();
		}
	}
	
	 /**
     * Copy bytes from an InputStream to an OutputStream.
     * @param input the InputStream to read from
     * @param output the OutputStream to write to
     * @return the number of bytes copied
     * @throws IOException In case of an I/O problem
     */
    public static int copy(
            InputStream input,
            OutputStream output)
                throws IOException {
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int count = 0;
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }


}
